package zhihuilan.controlle;

import com.wechat.pay.java.core.exception.ValidationException;
import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.service.payments.model.Transaction;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.refund.RefundService;
import com.wechat.pay.java.service.refund.model.AmountReq;
import com.wechat.pay.java.service.refund.model.CreateRequest;
import com.wechat.pay.java.service.refund.model.Refund;
import com.wechat.pay.java.service.refund.model.Status;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import zhihuilan.config.WeChatPayMiniConfig;
import zhihuilan.entity.MyPayOrder;
import zhihuilan.service.MyPayOrderService;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("/pay")
public class PayController {

    @Autowired
    private MyPayOrderService payOrderService;



    /**
     * 微信支付回调
     *
     * @return 回调结果
     */
    @PostMapping("/notify")
    public ResponseEntity.BodyBuilder wechat(@RequestBody String body, HttpServletRequest request) {
        try {
            WeChatPayMiniConfig weChatPayMiniConfig = new WeChatPayMiniConfig();
            // 构造 RequestParam
            RequestParam requestParam = new RequestParam.Builder()
                    // 序列号
                    .serialNumber(request.getHeader("Wechatpay-Serial"))
                    // 随机数
                    .nonce(request.getHeader("Wechatpay-Nonce"))
                    // 签名
                    .signature(request.getHeader("Wechatpay-Signature"))
                    // 时间戳
                    .timestamp(request.getHeader("Wechatpay-Timestamp"))
                    .body(body)
                    .build();
            // 初始化解析器
            NotificationParser parser = new NotificationParser((NotificationConfig) weChatPayMiniConfig.getConfig());
            // 验签、解密并转换成 Transaction
            Transaction transaction = parser.parse(requestParam, Transaction.class);
            // 校验交易状态
            if (Transaction.TradeStateEnum.SUCCESS.equals(transaction.getTradeState())) {
                // 支付成功，根据订单编号查询订单信息
                // 1.查询订单信息
                MyPayOrder orderOld = payOrderService.selectOrderByOrderId(transaction.getOutTradeNo());
                // 校验金额
                if (orderOld != null && orderOld.getAmount().equals(transaction.getAmount().getTotal())) {
                    // 金额相等 完成支付 更新订单状态
                    payOrderService.success(orderOld,transaction);
                } else {
                    // 金额异常 执行退款
                    payOrderService.refunded(transaction);
                }
            }
        } catch (ValidationException e) {
            // 签名验证失败，返回 401 UNAUTHORIZED 状态码
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED);
        }

        // 处理成功，返回 200 OK 状态码
        return ResponseEntity.status(HttpStatus.OK);
    }




}
